<?php
	header("Content-type:text/html;charset=utf-8");
	// require_once 'AppConfig.php';
	require_once 'AppUtil.php';


class tl2{
	var $pconfig = null;

	function __construct(){
		$payment = Model()->table('payment')->where([
            'payment_code' => 'tl2'
        ])->find();

        $this->pconfig = $pconfig = unserialize($payment['payment_config']);
	}


	function submit(){
		$this->pay();
	}

	function pay(){
		 $orderInfo = Model()->table('order')->where([
            'pay_sn' => $_REQUEST['pay_sn']
        ])->find();
        if (!$orderInfo) {
            showMessage("订单不存在！", '/shop/index.php?act=member_order&op=index', 'html', 'error');
            exit;
        }
//        print_r($orderInfo);
        if ($orderInfo['order_state'] != 10) {
            showMessage("订单不可支付！", '/shop/index.php?act=member_order&op=index', 'html', 'error');
            exit;
        }
        
        $pconfig = $this->pconfig;
	//print_r($_POST);

		$ogoods = Model()->table("order_goods")->where([
			'order_id' => $orderInfo['order_id']
		])->select();

		$params = array();
		$params["cusid"] = $pconfig['merchant_code'];
	    $params["appid"] = $pconfig['appid'];
	    $params["version"] = '11';
	    $params["trxamt"] = $orderInfo['order_amount'] * 100;
	    $params["reqsn"] = $orderInfo['order_sn'];//订单号,自行生成
	    $params["paytype"] = $_POST['tltype'];
	    $params["randomstr"] = "1450432107647";//
	    $params["body"] = $ogoods[0]['goods_name'];
	    $params["remark"] = "";
	    $params["acct"] = '';
	    $params["limit_pay"] = "no_credit";
        $params["notify_url"] = SHOP_SITE_URL . "/api/payment/tl2/notify_url.php";
	    $params["sign"] = AppUtil::SignArray($params,$pconfig['signkey']);//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = $pconfig['address'] . "/pay";

	    //$this->cancel($orderInfo);
	    
	    $rsp = $this->request($url, $paramsStr);

	    // echo "<br/>";
	    $rspArray = json_decode($rsp, true); 
	    // if($this->validSign($rspArray)){
	    // 	echo "验签正确,进行业务处理";
	    // }
	    // 
	    Language::read('common,home_layout');
	    Language::read('home_cart_index');
	    $this->member_info = ml('member')->find($_SESSION['member_id']);
	    Tpl::output('member_info', $this->member_info);
	    Tpl::output('nav_list', rkcache('nav', true));
        Tpl::setDir('buy');	
        Tpl::setLayout('buy_layout');
	    if($rspArray['retcode'] == 'SUCCESS'){
	     	Tpl::output('code_url',$rspArray['payinfo']);
            Tpl::output('order_sn',$orderInfo['order_sn']);
            Tpl::showpage('buy_weixinpay');
	    }
	    else{
        	showMessage('支付失败，请联系网站管理员','/shop/index.php?act=member_order','html','error');
	    }
	}

	function mobile_get_code(){
		$orderInfo = Model()->table('order')->where([
            'pay_sn' => $_REQUEST['pay_sn']
        ])->find();
        $params = array();
		$params["cusid"] = $this->pconfig['merchant_code'];
	    $params["appid"] = $this->pconfig['appid'];
	    $params["version"] = '11';
	    $params["trxamt"] = $orderInfo['order_amount'] * 100;
	    $params["reqsn"] = $orderInfo['order_sn'];//订单号,自行生成
	    $params["paytype"] = "W01";
	    $params["randomstr"] = "1450432107647";//
	    $params["body"] = $ogoods[0]['goods_name'];
	    $params["remark"] = "";
	    $params["acct"] = '';
	    $params["limit_pay"] = "no_credit";
        $params["notify_url"] = SHOP_SITE_URL . "/api/payment/tl2/notify_url.php";
	    $params["sign"] = AppUtil::SignArray($params,$this->pconfig['signkey']);//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = $this->pconfig['address'] . "/pay";

	    // $this->cancel($orderInfo);

	    $rsp = $this->request($url, $paramsStr);
	    // echo "<br/>";
	    $rspArray = json_decode($rsp, true); 
	    return $rspArray;
	}
	
	//当天交易用撤销
	function cancel($orderInfo){
	//print_r($this->pconfig);
		$params = array();
		$params["cusid"] = $this->pconfig['merchant_code'];
	    $params["appid"] = $this->pconfig['appid'];
	    $params["version"] = '11';
	    $params["trxamt"] = $orderInfo['order_amount'] * 100;;
	    $params["reqsn"] = $orderInfo['pay_sn'];
	    $params["oldreqsn"] = $orderInfo['pay_sn'];//原来订单号
	    $params["randomstr"] = "1450432107647";//
	    $params["sign"] = AppUtil::SignArray($params,$this->pconfig['signkey']);//签名
	    $paramsStr = AppUtil::ToUrlParams($params);
	    $url = $this->pconfig['address'] . "/cancel";
	    $rsp = $this->request($url, $paramsStr);
	//	echo "请求返回:".$rsp;
	    // echo "<br/>";
	    // $rspArray = json_decode($rsp, true); 
	    // if(validSign($rspArray)){
	    	// echo "验签正确,进行业务处理";
	    // }
	}
	
	// //当天交易请用撤销,非当天交易才用此退货接口
	// function refund(){
	// 	$params = array();
	// 	$params["cusid"] = AppConfig::CUSID;
	//     $params["appid"] = AppConfig::APPID;
	//     $params["version"] = AppConfig::APIVERSION;
	//     $params["trxamt"] = "1";
	//     $params["reqsn"] = "1234567889";
	//     $params["oldreqsn"] = "123456";//原来订单号
	//     $params["randomstr"] = "1450432107647";//
	//     $params["sign"] = AppUtil::SignArray($params,AppConfig::APPKEY);//签名
	//     $paramsStr = AppUtil::ToUrlParams($params);
	//     $url = AppConfig::APIURL . "/refund";
	//     $rsp = request($url, $paramsStr);
	// 	echo "请求返回:".$rsp;
	//     echo "<br/>";
	//     $rspArray = json_decode($rsp, true); 
	//     if(validSign($rspArray)){
	//     	echo "验签正确,进行业务处理";
	//     }
	// }
	
	// function query(){
	// 	$params = array();
	// 	$params["cusid"] = AppConfig::CUSID;
	//     $params["appid"] = AppConfig::APPID;
	//     $params["version"] = AppConfig::APIVERSION;
	//     $params["reqsn"] = "123456";
	//     $params["randomstr"] = "1450432107647";//
	//     $params["sign"] = AppUtil::SignArray($params,AppConfig::APPKEY);//签名
	//     $paramsStr = AppUtil::ToUrlParams($params);
	//     $url = AppConfig::APIURL . "/query";
	//     $rsp = request($url, $paramsStr);
	// 	echo "请求返回:".$rsp;
	//     echo "<br/>";
	//     $rspArray = json_decode($rsp, true); 
	//     if(validSign($rspArray)){
	//     	echo "验签正确,进行业务处理";
	//     }
	// }
	
	//发送请求操作仅供参考,不为最佳实践
	function request($url,$params){
		$ch = curl_init();
		$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
		curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		 
		$output = curl_exec($ch);
		curl_close($ch);
		return  $output;
	}
	
	// //验签
	function validSign($array){
		if("SUCCESS"==$array["retcode"]){
			$signRsp = strtolower($array["sign"]);
			$array["sign"] = "";
			$sign =  strtolower(AppUtil::SignArray($array, $this->pconfig['signKey']));
			if($sign==$signRsp){
				return TRUE;
			}
			else {
				echo "验签失败:".$signRsp."--".$sign;
			}
		}
		else{
			echo $array["retmsg"];
		}
		
		return FALSE;
	}

  	function notify_verify()
    {
		$params = array();
		foreach($_POST as $key=>$val) {//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
			$params[$key] = $val;
		}

		if(count($params)<1){//如果参数为空,则不进行处理


			exit();
		}
		if(AppUtil::ValidSign($params, $this->pconfig['signKey'])){//验签成功
			//此处进行业务逻辑处理
			$this->pay_result = true;
	            return true;
		}
		else{
			return false;
		}
    }
	function return_verify(){
        return $this->notify_verify();
    }
	public function getPayResult($parms){
        return $this->pay_result;
    }
}